var fs ;

window.requestFileSystem  = window.requestFileSystem || window.webkitRequestFileSystem;

function toArray(list) {
  return Array.prototype.slice.call(list || [], 0);
}

function errorHandler(e) {
  var msg = '';

  switch (e.code) {
    case FileError.QUOTA_EXCEEDED_ERR:
      msg = 'QUOTA_EXCEEDED_ERR';
      break;
    case FileError.NOT_FOUND_ERR:
      msg = 'NOT_FOUND_ERR';
      break;
    case FileError.SECURITY_ERR:
      msg = 'SECURITY_ERR';
      break;
    case FileError.INVALID_MODIFICATION_ERR:
      msg = 'INVALID_MODIFICATION_ERR';
      break;
    case FileError.INVALID_STATE_ERR:
      msg = 'INVALID_STATE_ERR';
      break;
    default:
      msg = 'Unknown Error';
      break;
  };

  console.log('Error: ' + msg);
}

function listResults(entries) {
  // Document fragments can improve performance since they're only appended
  // to the DOM once. Only one browser reflow occurs.
  var fragment = document.createDocumentFragment();

    entries.forEach(function(entry, i) {
	var img = entry.isDirectory ? '<img src="/img/folderIcon.gif" width="20" height="20">' :
            '<img src="img/file_icon.jpg" width="20" height="20">';
	var li = document.createElement('li');
	li.innerHTML = [img, '<span>', entry.name, entry.size, '</span>'].join('');
	fragment.appendChild(li);
    });
    
    document.querySelector('#filelist').appendChild(fragment);
}

function configurePage() {
    // need to add a handler which figures out what to do when we drop something on the droppable section...
    window.requestFileSystem(window.PERSISTENT, 5*1024*1024,
			     function(filesystem) {
				 fs = filesystem;
				 console.log('filesystem got!');

				 var dirReader = fs.root.createReader();
				 var entries = [];
				 
				 // Call the reader.readEntries() until no more results are returned.
				 var readEntries = function() {
				     dirReader.readEntries (function(results) {
					 if (!results.length) {
					     listResults(entries.sort());
					 } else {
					     entries = entries.concat(toArray(results));
					     readEntries();
					 }
				     }, errorHandler);
				 };
				 
				 readEntries(); // Start reading dirs.

			     }, errorHandler);

}
